<template>
    <div>
        <vxe-toolbar custom  ref="toolbarRef" >
            <template #buttons>
                <el-button
                        type="primary"
                        icon="el-icon-plus"
                        @click="handleAdd"
                        v-if="this.editable"
                >
                    新 增
                </el-button>
            </template>
            <template #tools>

                <el-tooltip content="清空筛选" placement="top">
                <vxe-button  icon="vxe-icon-delete" class="tool-btn" @click="$refs.tableRef.clearFilter()" circle></vxe-button>
                </el-tooltip>
             <vxe-button  icon="vxe-icon-refresh" class="tool-btn" @click="refresh" circle style="margin-right: 12px;"></vxe-button>
      </template>
        </vxe-toolbar>
        <vxe-grid
                v-bind="gridOptions"
                id="tableRef"
                ref="tableRef"
                show-footer
                class="mytable-scrollbar"
                :data="list"
                :edit-rules="validRules"
                :tooltip-config="{ zIndex: 9999 }"
                :customConfig="customConfig"
                :menu-config="menuConfig"
                :footer-method="footerMethod"
                :edit-config="{
                trigger: 'click',
                mode: 'row',
                showUpdateStatus: true,
                showInsertStatus: true,
                beforeEditMethod:beforeEdit}"
                @edit-closed="editClosedEvent"
                @edit-actived="editActivedEvent"
                @menu-click="contextMenuClickEvent">
            <!--<vxe-column type="checkbox" width="50"></vxe-column>-->

            <template #prodNum_edit="scope">
                <vxe-input v-model="scope.row.prodNum" type="integer" min="0" max="99999999" :controls="false"
                           @change="(value)=>calTotalPrice(scope.row.price,value.value,scope)"
                           @blur="(value)=>calculateTotals(scope.row.prodNum, scope.row)"
                          ></vxe-input>
            </template>

            <template #planOkDate_edit="scope">
                <el-date-picker v-model="scope.row.planOkDate" type="date" transfer format="YYYY-MM-DD" @change="updateStatus(scope)"
                                value-format="YYYY-MM-DD" ></el-date-picker>
            </template>

            <template #price_edit="scope">
                <!--<vxe-input v-model="row.tabNo" type="text"></vxe-input>-->
                <vxe-input v-model="scope.row.price" type="float" digits="2"  max="99999999" :controls="false"  @change="(value)=>calTotalPrice(value.value,scope.row.prodNum,scope)"
                           ></vxe-input>
            </template>
            <template #labelColor_edit="scope">
                <!--<vxe-input v-model="row.tabNo" type="text"></vxe-input>-->
                <el-select v-model="scope.row.labelColor"
                           :clearable="true"
                           :filterable="true"
                           placeholder="请选择箱唛颜色"
                           type="string" transfer>
                    <el-option
                            v-for="item in labelColorDic"
                            :key="item.dictValue"
                            :value="item.dictValue"
                            :label="item.dictValue"/>
                </el-select>
            </template>

            <template #deliAddr_edit="scope">
                <el-select v-model="scope.row.deliAddr"
                           :clearable="true"
                           :filterable="true"
                           :allow-create="true"
                           placeholder="请选择交货地址"
                           type="string" transfer>
                    <el-option
                            v-for="item in supplierDic"
                            :key="item.supName"
                            :value="item.supName"
                            :label="item.supName"/>
                </el-select>
            </template>

            <template #btn_default="{ row }">
                <template v-if="!isActiveStatus(row) && this.editable">
                    <!--<el-tooltip content="修改" placement="top">-->
                    <!--<el-button-->
                    <!--size="small"-->
                    <!--type="primary"-->
                    <!--@click="handleUpdate(row)"-->
                    <!--&gt;修改-->
                    <!--</el-button>-->
                    <!--</el-tooltip>-->
                    <el-tooltip content="子料外发" placement="top" v-if="row.isChild!='是'">
                        <el-button
                                icon="Switch"
                                link
                                size="small"
                                type="primary"
                                @click="handleChild(row)"
                        ></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                        <el-button
                                icon="el-icon-delete"
                                link
                                size="small"
                                type="primary"
                                @click="handleDelete(row)"
                        ></el-button>
                    </el-tooltip>
                </template>
                <template v-else>
                    <!--<el-tooltip content="保存" placement="top">-->
                    <!--<el-button-->
                    <!--size="small"-->
                    <!--type="primary"-->
                    <!--@click="handleSaveRow(row)"-->
                    <!--&gt;保存-->
                    <!--</el-button>-->
                    <!--</el-tooltip>-->
                    <!--<template v-if="!row.id && this.editable">-->
                        <!--<el-tooltip content="取消" placement="top">-->
                            <!--<el-button-->
                                    <!--size="small"-->
                                    <!--@click="handleDelete(row)"-->
                            <!--&gt;取消-->
                            <!--</el-button>-->
                        <!--</el-tooltip>-->
                    <!--</template>-->
                </template>
            </template>
        </vxe-grid>
        <select-order-item ref="selectOrderItemRef" @setOrderItemList="setOrderItemList"></select-order-item>
        <select-child ref="selectChildRef" @success="setChild"></select-child>
         <!--<div style="margin-top:20px">-->
            <!--<vxe-pager -->
            <!--v-model:current-page="page.currentPage" -->
            <!--v-model:page-size="page.pageSize" -->
            <!--:total="page.total"-->
            <!--@page-change='pageChange'-->
            <!--background-->
            <!--:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes',  'Total']"-->
             <!--size="small" -->
             <!--/>-->
         <!--</div>-->
        <el-dialog title="请选择工序" append-to-body v-model="box" width="60%">
            <el-tree
                    :default-expand-all="true"
                    :check-strictly="true"
                    :data="workListData"
                    show-checkbox
                    node-key="id"
                    ref="treeMenu"
                    :props="props"
                    @check-change="menuCheck"
                    :render-content="renderContent"
            >
            </el-tree>
            <template #footer>
                <span class="dialog-footer">
                  <el-button @click="this.box = false">取 消</el-button>
                  <el-button type="primary" @click="setItemWorkList">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import {getList, getDetail, add, update} from "@/api/anwise/customer/customer_factory";
    import {checkByCalc, workListSelect} from "@/api/anwise/material/bom_list";
    import {findList, remove} from "@/api/anwise/prod/prod_item";
    import {calcChildNum, overflowNum} from "@/api/anwise/prod/prod_main";

    import {mapGetters} from "vuex";
    import {VXETable} from 'vxe-table'
    import {getDictionary} from "@/api/system/dictBiz"
    import {select} from "@/api/base/region";
    import {Pattern} from "@/utils/validate.js";
    import selectOrderItem from './select_order_item.vue';
    import selectChild from './select_child.vue';
    import {select as supplierSelect} from "@/api/anwise/supplier";
    import {markRaw} from "vue"


    export default {
        components: {
            selectOrderItem,
            selectChild,
        },
        data() {
            return {
                props: {
                    label: 'nodeName',
                    value: 'id',
                },
                ifullscreen:false,
                tabNo:'',
              tabDate:'',
                editRow:{},
                rowIndex:'',
                box: false,
                workListTips:'',
                workListData:[],
                workListList:[],
                labelColorDic:[],
                workPrice:[],
                supplierId:'',
                isEdit:false,
                iconSearch:true,
                customerId:undefined,
                provinceList:[],
                cityList:[],
                editable:true,
                list: [],
                customConfig: {
                    storage: true,
                    checkMethod({column}) {
                        if (['facName'].includes(column.field)) {
                            return false
                        }
                        return true
                    },
                },
                menuConfig: {},
                form: {},
                query: {},
                loading: true,
                data: [],
                selectionList: [],
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                subVisible: false,
                direction: 'rtl',
                customerName: "安伟客户表",
                customerTypeList: [],
                nameOptions: [{data: null}],
                validRules: {
                    orderNo: [
                        {required: true, message: '订单号码必须填写'}
                    ],
                    orderItem: [
                        {required: true, message: '订单项必须填写'}
                    ],
                    prodNum: [
                        {required: true, message: '生产数量必须填写'}
                    ],
                    planOkDate:[
                        {required: true, message: '生产完成日期必须填写'}
                    ],
                    price: [
                        {required: true, message: '单价必须填写'}
                    ],
                    workList: [
                        {required: true, message: '加工工序不能为空'}
                    ],

                },
                gridOptions: {
                    height: '400px',
                    border: true,
                    showOverflow: true,
                    keepSource: true,
                    size: "medium",
                    rowConfig: {
                        // keyField: 'id',
                        isHover: true
                    },
                    columnConfig: {
                        resizable: true
                    },
                    // editRules: ,
                    columns: [
                        // {type: 'checkbox', width: 50, fixed:'left', visible: true},
                        // {type: 'seq', width: 50, fixed:'left', align: "center"},
                        // {
                        //     title: "生产单单号",
                        //     field: "tabNo",
                        //     maxlength:1000,
                        //     minWidth: 150,
                        //     fixed:'left',
                        // },
                        {
                            title: "生产单项",
                            field: "tabItem",
                            maxlength:1000,
                            minWidth: 80,
                            fixed:'left',
                        },
                        {
                            title: "订单号码",
                            field: "orderNo",
                            minWidth: 150,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "订单项",
                            field: "orderItem",
                            minWidth: 80,
                        },
                        {
                            title: "物料编号",
                            field: "materialNo",
                            minWidth: 150,
                         filters: [{ data: '' }],
                        filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "客户条码",
                            field: "barcode",
                            minWidth: 200,
                        },
                        {
                            title: "物料名称",
                            field: "materialName",
                            width: 200,
                        },
                        {
                            title: "类别",
                            field: "category",
                            width: 100,
                        },
                        {
                            title: "单位",
                            field: "unit",
                            minWidth: 100,
                        },
                        {
                            title: "订单数量",
                            field: "orderNum",
                            width: 120,
                        },
                        {
                            title: "生产数量",
                            field: "prodNum",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'prodNum_edit'}
                        },

                        {
                            title: "生产完成日期",
                            field: "planOkDate",
                            minWidth: 140,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'planOkDate_edit'}
                        },
                        {
                            title: "交货地点",
                            field: "deliAddr",
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'deliAddr_edit'},
                            width: 200,
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "订单交货日期",
                            field: "orderDeliDate",
                            minWidth: 140,
                        },
                        {
                            title: "加工工序",
                            field: "workList",
                            minWidth: 200,
                            editRender: {name: 'input', attrs: {placeholder: '请输入加工工序',readonly:true},events: {click: this.selectWorkList}},
                            // slots: {edit: 'workList_edit'}
                        },

                        {
                            title: "单价",
                            field: "price",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'price_edit'}
                        },
                        {
                            title: "金额",
                            field: "totalPrice",
                            minWidth: 120,
                        },
                        {
                            title: "箱唛",
                            field: "packLabel",
                            minWidth: 350,
                            editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                        },
                        {
                            title: "箱唛颜色",
                            field: "labelColor",
                            minWidth: 120,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'labelColor_edit'}
                        },
                        // {
                        //     title: "已交数量",
                        //     field: "okNum",
                        //     minWidth: 120,
                        // },
                        // {
                        //     title: "交货已完成",
                        //     field: "isCompleted",
                        //     minWidth: 120,
                        // },
                        // {
                        //     title: "每外箱数量",
                        //     field: "maxNum",
                        //     minWidth: 120,
                        // },
                        // {
                        //     title: "每内箱数量",
                        //     field: "minNum",
                        //     minWidth: 120,
                        // },
                        // {
                        //     title: "每袋数量",
                        //     field: "saveNum",
                        //     minWidth: 120,
                        // },
                        // {
                        //     title: "包装体积",
                        //     field: "packSize",
                        //     minWidth: 100,
                        // },
                        {
                            field: 'btn',
                            title: '操作',
                            minWidth: 120,
                            align: "center",
                            fixed: "right",
                            visible: true,
                            slots: {default: 'btn_default'}
                        }
                    ]
                },
                supplierDic:[]
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.customer_add, false),
                    viewBtn: this.validData(this.permission.customer_view, false),
                    delBtn: this.validData(this.permission.customer_delete, false),
                    editBtn: this.validData(this.permission.customer_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            },
            subIds() {
                let ids = [];
                this.selectionListSub.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
            this.isEdit = false;
            this.disabledCommit(false);
            this.init();
            this.$nextTick(() => {
                console.log(this.$refs.tableRef)
                console.log(this.$refs.toolbarRef)
                this.$refs.tableRef.connect(this.$refs.toolbarRef);
            })
        },
        methods: {
            genPrice(workPrice) {
              this.workPrice = workPrice;
                const $table = this.$refs.tableRef
                // let changeList = [];
                // changeList.push(...$table.getInsertRecords());
                // changeList.push(...$table.getUpdateRecords());
                console.log("$table.getInsertRecords()",$table.getInsertRecords());
                if ($table.getInsertRecords().length >0) {
                    $table.getInsertRecords().map(it =>{
                        if (this.workPrice && this.workPrice.length > 0) {
                            this.workPrice.forEach(item => {
                                if (item.workList == it.workList && item.materialNo == it.materialNo
                                    && new Date(this.tabDate).getTime() >=new Date(item.activeDate)) {
                                    it.price = item.taxExclusivePrice;
                                    if (it.prodNum) {
                                        it.totalPrice = this.$toFixed(it.prodNum * item.taxExclusivePrice,2);
                                    }
                                }
                            })
                        }
                    })
                }
            },
            beforeEdit({ row, rowIndex, column, columnIndex }) {
                if (this.editable) {

                }
                return this.editable;
            },
            handleFullScreen() {
                this.ifullscreen = !this.ifullscreen;
            },
            init(){
                supplierSelect().then(res=>{
                    this.supplierDic = res.data.data;
                })
                getDictionary({ code: 'label_color' }).then(res => {
                    this.labelColorDic = res.data.data;
                });

            },
            updateStatus(scope){
                this.$refs.tableRef.updateStatus(scope);
            },
            calcSum(list, field) {
                let count = 0
                list.forEach(item => {
                    count += Number(item[field])
                })
                if (field == 'totalPrice') {
                    return this.$toFixed(count,2);
                } else {
                    return this.$toFixed(count,0);
                }
            },
            // 在值发生改变时更新表尾合计
            updateFooterEvent (params) {
                let xTable = this.$refs.tableRef
                xTable.updateFooter()
            },
            footerMethod(table) {
                console.log("table",table);
                return [
                    table.columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计'
                        }
                        if (['orderNum', 'prodNum','totalPrice'].includes(column.field)) {
                            return this.calcSum(table.data, column.field)
                        }
                        return null
                    })
                ]
            },
           setChild(row) {
                let form  = this.editRow;
                form.isChild = '是';
                form.childNo = row.nodeNo;
                calcChildNum(form).then(res => {
                    console.log(res.data.data);
                    let material = res.data.data;
                    let price = 0;
                    let totalPrice= 0;
                    if (this.workPrice && this.workPrice.length > 0) {
                       this.workPrice.forEach(work => {
                            if (work.materialNo === row.nodeNo && work.workList =='全部'
                                && new Date(this.tabDate).getTime() >=new Date(work.activeDate)) {
                                price = work.taxExclusivePrice;
                            }
                        })
                    }
                    let existsNum = 0;
                    this.$refs.tableRef.getTableData().fullData.forEach(e => {
                        if (e.orderNo == this.editRow.orderNo && e.orderItem === this.editRow.orderItem && e.materialNo == material.materialNo  && !e.id) {
                            existsNum  = existsNum+e.prodNum;
                        }
                    })
                    let prodNum = material.defaultNum -  existsNum;
                    if (prodNum < 0) {
                        prodNum = 0;
                    }
                    // this.editRow.orderNum = res.data.data;
                    this.editRow.maxNum = material.limitNum;
                    this.editRow.prodNum = prodNum;
                    this.editRow.materialNo = material.materialNo;
                    this.editRow.materialName = material.materialName;
                    this.editRow.bacode = material.barCode;
                    this.editRow.specification = material.specification;
                    this.editRow.category = material.type;
                    this.editRow.price = price;
                    this.editRow.totalPrice = this.$toFixed(price * prodNum,2);
                    this.editRow.isChild = '是';
                    this.editRow.packLabel='';
                    this.editRow.labelColor='';
                })
            },
            handleChild(row) {
                this.editRow = row;
                this.$refs.selectChildRef.showSelect(row.materialNo);
            },
            setItemWorkList() {
                const workListCheck = this.$refs.treeMenu.getCheckedNodes(false, true);
                let workListTips = "";
                let workListIds = "";
                workListCheck.forEach(item => {
                    workListTips += item.level+":"+item.nodeName+"-"+item.parentNo+"/";
                    workListIds+= item.id+",";
                });
                console.log(workListTips);
                if (workListTips.length > 0) {
                    workListTips = workListTips.substring(0, workListTips.length-1);
                    workListIds = workListIds.substring(0, workListIds.length-1);
                }
                let workListCount=0;
                this.workListList.forEach(res=>{
                    if(res.nodeNo === "工序"){
                        workListCount++;
                    }
                })
                console.log("workListCheck.length",workListCheck.length);
                console.log("this.workListList.length",this.workListList.length);
                if (workListCheck.length === workListCount) {
                    this.editRow.workList = "全部";
                } else {
                    this.editRow.workList = workListTips;
                }

                this.editRow.workListIds = workListIds;
                this.box = false;
                this.editRow.totalPrice = '';
                this.editRow.price = '';
                console.log("workListTips",workListTips);
                if (this.workPrice && this.workPrice.length > 0) {
                    this.workPrice.forEach(item => {
                        if (item.workList == this.editRow.workList && item.materialNo == this.editRow.materialNo) {
                            this.editRow.price = item.taxExclusivePrice;
                            if (this.editRow.prodNum) {
                                this.editRow.totalPrice = this.$toFixed(this.editRow.prodNum * item.taxExclusivePrice,2);
                            }
                        }
                    })
                }
            },
            renderContent(h, {data}){
                return h(
                    'span',
                    {
                        style: {
                            color: '#626AEF',
                        },
                    },
                    data.nodeName+" [<"+data.parentNo+">"+data.parentName+"]-("+(data.modelNo || '无工模')+")"
                )
            },
            menuCheck(data, isChecked) {
                console.log(this.$refs.treeMenu.getNode(data.id))
                if (isChecked) {
                    if (data.parentId) {
                        this.setParentCheck(data.id)
                    }
                } else {
                    this.setChildUncheck(data.id)
                }
            },
            setChildUncheck(id) {
                const node = this.$refs.treeMenu.getNode(id);
                if (node.data.children) {
                    node.data.children.forEach(item => {
                        this.$refs.treeMenu.setChecked(item.id, false);
                        this.setChildUncheck(item.id)
                    })
                }
            },
            setParentCheck(id) {
                const node = this.$refs.treeMenu.getNode(id);
                if (node.data.parentId) {
                    this.$refs.treeMenu.setChecked(node.data.parentId, true);
                    this.setParentCheck(node.data.parentId)
                }
            },
            selectWorkList(scope) {
                let row = scope.row;
                console.log("row",this.$refs.tableRef.getRowid());
                this.editRow = row;
                // checkByCalc(row.materialNo).then(res => {
                //     if (res.data.success) {
                        workListSelect(row.materialNo).then(res =>{
                            if (res.data.success) {
                                this.workListData = res.data.data.workTree;
                                this.workListList = res.data.data.workList;
                                this.ifullscreen = false;
                                this.box = true;
                            }
                        })
                //     } else {
                //         this.$message.error(res.data.msg || "当前物料Bom结构异常！");
                //     }
                // })
                setTimeout(() =>{
                    this.$nextTick(() => {
                        console.log("this.$refs.treeMenu", this.$refs.treeMenu);
                        if (row.workList == '全部') {
                            this.$refs.treeMenu.setCheckedNodes(this.workListList);
                        } else {
                            row.workListIds.split(',').forEach(id => {
                                this.$refs.treeMenu.setChecked(id, true);
                            })
                        }
                    });
                },1000)
            },
            calTotalPrice(price,num,scope) {
                console.log('price',price)
                console.log('num',num)
                this.$refs.tableRef.updateStatus(scope);
                let row=scope.row;
              if (price && num) {
                  row.totalPrice = this.$toFixed(price * num,2);
              }
            },
            overflowNum(num, row) {
                overflowNum(row).then(res => {
                    if (res.data.success) {
                        let existsNum = 0;
                        this.$refs.tableRef.getTableData().fullData.forEach((e,index) => {
                            console.log("eeeeeeeeeeeee", e);
                            if (e.orderNo == row.orderNo && e.orderItem === row.orderItem && e.materialNo == row.materialNo && e._X_ROW_KEY != row._X_ROW_KE) {
                                console.log("e.prodNum",e.prodNum);
                                existsNum  = existsNum + (e.prodNum ? 0 : Number(e.prodNum));
                            }
                        })
                        let prodNum  = res.data.data-existsNum ;
                        if (num && num > prodNum) {
                            row.prodNum = prodNum;
                            this.updateFooterEvent();
                            this.$message({
                                type: "warning",
                                message: "数量不能大于["+prodNum+"]!"
                            });
                        }
                    }
                })
                // if (row.isChild=='是') {
                //     if (num && num > row.limitNum * 1.05) {
                //         row.prodNum = (row.limitNum * 1.05).toFixed(2);
                //         this.$message({
                //             type: "warning",
                //             message: "数量不能大于["+row.limitNum * 1.05+"]!"
                //         });
                //     }
                // } else {
                //     if (num && num > row.orderNum) {
                //         row.prodNum = (row.orderNum ).toFixed(2);
                //     }
                // }
            },
            calculateTotals(num, row){
                overflowNum(row).then(res => {
                    console.log("row",row);
                    if (res.data.success) {
                        let existsNum = 0;
                        this.$refs.tableRef.getTableData().fullData.forEach(e => {
                            console.log("eeeeeeeeeeeee", e);
                            if (e.orderNo == row.orderNo && e.orderItem === row.orderItem && e.materialNo == row.materialNo && e._X_ROW_KEY != row._X_ROW_KEY && !e.id) {
                                console.log("e.prodNum",e.prodNum);
                                existsNum  = existsNum+e.prodNum;
                            }
                        })
                        console.log("existsNum",existsNum);
                        let prodNum  = res.data.data-existsNum ;
                        console.log("prodNum",prodNum);
                        if (num && num > prodNum) {
                            row.prodNum = prodNum;
                            if (row.price && row.prodNum) {
                                row.totalPrice = row.price * row.prodNum;
                            }
                            this.updateFooterEvent();
                            this.$message({
                                type: "warning",
                                message: "数量不能大于["+prodNum+"]!"
                            });
                        }
                    }
                })
            },
            async setOrderItemList(list) {
                const $table = this.$refs.tableRef
                let selectData = markRaw(list);
                console.log(selectData)
                if (list.length > 0) {
                    this.$emit("disabledFiled", true);
                }
                let $this = this;
                if (!$table.getEditRecord()) {
                    selectData.forEach(await function(item) {
                        // if (!$table.getTableData().fullData.some((val) => (val.orderNo === item.idNo && val.orderItem === item.itemNo && val.materialNo == item.materialNo))) {
                        let price = 0.00;
                        let totalPrice = 0.00;
                        let maxNo = 0;
                        if ($this.$refs.tableRef.getTableData().fullData.length > 0) {
                            maxNo = Number($this.$refs.tableRef.getTableData().fullData[$this.$refs.tableRef.getTableData().fullData.length - 1].tabItem);
                        }
                        console.log("this.workPrice", $this.workPrice);
                        if ($this.workPrice && $this.workPrice.length > 0) {
                            $this.workPrice.forEach(work => {
                                if (work.materialNo === item.materialNo && work.workList == '全部'
                                    && new Date($this.tabDate).getTime() >=new Date(work.activeDate)) {
                                    price = work.taxExclusivePrice;
                                    // totalPrice = (price * item.num).toFixed(2);
                                }
                            })
                        }
                        console.log("this.$refs.tableRef.getTableData().fullData.length", $this.$refs.tableRef.getTableData().fullData.length);
                        let existsNum = 0;
                        $this.$refs.tableRef.getTableData().fullData.forEach(e => {
                            if (e.orderNo == item.idNo && e.orderItem === item.itemNo && e.materialNo == item.materialNo && !e.id) {
                                existsNum  = existsNum+e.prodNum;
                            }
                        })
                        let prodNum = item.num - item.prodNum -  existsNum;
                        if (prodNum < 0) {
                            prodNum = 0;
                        }
                        console.log("type",item.type)
                        console.log(item.type="成品")
                        let mat = {
                            // id: '',
                            tabItem: maxNo + 1,
                            orderNo: item.idNo,
                            orderItem: item.itemNo,
                            barcode: item.barCode,
                            materialNo: item.materialNo,
                            materialName: item.materialName,
                            materialType: item.materialType,
                            category: item.type,
                            specification: item.materialType,
                            orderNum: item.num,
                            prodNum: prodNum,
                            unit: item.unit,
                            price: price,
                            totalPrice: $this.$toFixed(price * prodNum,2),
                            // packLabel: item.salesName+(item.salesName ? '\n' :'')+item.packLabelContent,
                            packLabel: item.packLabelContent,
                            labelColor: item.labelColor,
                            orderDeliDate: item.deliDate,
                            planOkDate:item.deliDate,
                            workList: '全部',
                            isChild: '否',
                            maxNum:item.maxNum,
                            minNum:item.minNum,
                            saveNum:item.saveNum,
                            packRemark:item.packRemark,
                            packSize:item.packSize,
                            $cellEdit: true
                        }
                        // this.list.push(mat);
                        $this.$refs.tableRef.insertAt(mat, -1);
                        console.log($this.list);

                        // }
                    });
                }
            },
            refresh(){
               this.page = {
                   pageSize: 10,
                   currentPage: 1,
               }
               this.query = {}
               this.onLoad(this.page)
            },
            pageChange(e){
               this.page = {
                    pageSize: e.pageSize,
                    currentPage: e.currentPage,
               }
               this.onLoad(this.page)
            },


            isActiveStatus(row) {
                const $table = this.$refs.tableRef
                if ($table) {
                    return $table.isEditByRow(row)
                }
            },
            handleAdd() {
                if (!this.tabDate) {
                    this.$message({
                        type: "error",
                        message: "请先选择排单日期!"
                    });
                    return;
                }
                console.log("this.list",this.list);
                this.$refs.selectOrderItemRef.showSelect();
                // this.isEdit = true;
                // const $table = this.$refs.tableRef
                // if (!$table.getEditRecord()) {
                //     console.log(this.tableRef)
                //     if ($table) {
                //         const obj = $table.insertAt({}, -1).then(res => {
                //             $table.setEditCell(res.row, 'facName');
                //         })
                //         console.log(obj)
                //         // this.searchShow = false
                //         // this.iconSearch = false
                //     }
                // }
            },
            contextMenuClickEvent(data) {
                const menu = data.menu;
                const row = data.row;
                const column = data.column;
                const $table = this.$refs.tableRef
                if ($table) {
                    switch (menu.code) {
                        case 'hideColumn':
                            $table.hideColumn(column)
                            break
                        case 'showAllColumn':
                            $table.resetColumn(true)
                            break
                        case 'copy':
                            // if (XEClipboard.copy(row[column.field])) {
                            //   ElMessage.success('保存成功')
                            // }
                            // ElMessage.success('复制成功')
                            break
                        case 'reload':
                            //  findList()
                            break
                        case 'insertAt':
                            $table.insertAt({}, row || -1).then(({row}) => {
                                $table.setEditCell(row, column || 'name')
                            })
                            break
                        case 'remove':
                            $table.remove(row)
                            break
                        case 'save':
                            // ElMessage.success('保存成功')
                            break
                    }
                }
            },
            disabledCommit(data) {
                this.$emit("disabledCommit",data);
            },
            editActivedEvent(row){//激活单元格事件
                this.isEdit = true;
                this.disabledCommit(true);
            },
            editClosedEvent(row) {
                console.log(row)
                const $table = this.$refs.tableRef;
                $table.clearValidate();
                this.disabledCommit(false);
                // const $table = this.$refs.tableRef
                // console.log($table.getTableData().fullData);
                // const err = this.validEvent(row.row);
                // if (err) {
                //     return
                // }
                // if (row.column.field=='prodNum') {
                //     this.overflowNum(row.row.prodNum, row.row);
                // }

            },
            async handleSaveRow(row) {
                const err = await this.validEvent(row);
                if (err) {
                    return
                }

            },
            async validEvent(row) {
                const $table = this.$refs.tableRef
                const errMap = await $table.validate(row).catch(errMap => errMap)
                return errMap;

            },
            setData(editable,tabNo,supplierId) {
                // if (list)
                //     this.list = list;

                if(tabNo){
                    this.query.tabNo = tabNo
                    this.tabNo = tabNo
                    this.supplierId = supplierId;
                }
                console.log("aaaaaa", this.tabNo)
               // this.customerId = customerId
                this.onLoad(this.page)

                this.editable = editable;
                console.log(this.editable);
            },
            formatType(value) {
                let value2 = "";
                this.customerTypeList.forEach(res => {
                    if (value === res.dictKey) {
                        value2 = res.dictValue;
                    }
                });
                return value2
            },

            // 主表模块
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            async handleDelete(row) {
                console.log("row",this.list);
                const $table = this.$refs.tableRef
                if (row.id) {
                    this.$confirm('是否确认删除?', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        if ($table.getTableData().fullData.length === 1) {
                            this.$emit("disabledFiled", false);
                        }
                        $table.remove(row)

                    }).then(()=>{
                        this.$message({type: "success", message: "操作成功，保存后生效!"});
                    })
                } else {
                    if ($table.getTableData().fullData.length === 1) {
                        this.$emit("disabledFiled", false);
                    }
                    $table.remove(row)

                }
            },
            // handleDelete() {
            //   if (this.selectionList.length === 0) {
            //     this.$message.warning("请选择至少一条数据");
            //     return;
            //   }
            //   this.$confirm("确定将选择数据删除?", {
            //     confirmButtonText: "确定",
            //     cancelButtonText: "取消",
            //     type: "warning"
            //   })
            //     .then(() => {
            //       return remove(this.ids);
            //     })
            //     .then(() => {
            //       this.onLoad(this.page);
            //       this.$message({
            //         type: "success",
            //         message: "操作成功!"
            //       });
            //       this.$refs.crud.toggleSelection();
            //     });
            // },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                if(this.$refs.crud)  this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            onLoad(page, params = {}) {
                this.query.tabNo = this.tabNo;
                if (this.$refs.tableRef.getInsertRecords().length>0 || this.$refs.tableRef.getRemoveRecords().length>0 ||
                    this.$refs.tableRef.getUpdateRecords().length>0) {
                    this.$confirm("搜索会丢失本次新增/编辑/删除的数据，确定继续吗?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    })
                        .then(() => {
                            this.loading = true;
                            console.log('aaaaaaaaaaaa', this.query)
                            findList(Object.assign(params, this.query)).then(res => {
                                const data = res.data.data;
                                // this.page.total = data.total;
                                this.list = data;
                                this.loading = false;
                                this.selectionClear();
                                this.isEdit = false;
                            });
                        })
                }else {
                    this.loading = true;
                    console.log('aaaaaaaaaaaa', this.query)
                    findList(Object.assign(params, this.query)).then(res => {
                        const data = res.data.data;
                        // this.page.total = data.total;
                        this.list = data;
                        this.loading = false;
                        this.selectionClear();
                        this.isEdit = false;
                    });
                }
            },

        }
    };
</script>

<style scoped>
:deep(.vxe-pulldown.size--medium){
    z-index: 99999 !important;
}
.vxe-table--tooltip-wrapper {
  z-index: 10000 !important;
}
:deep(.vxe-table--fixed-right-wrapper){
    z-index: 99999 !important;
}
</style>
